package jm.nj.demo23main.c_dbUtils;

import jm.nj.demo23main.c_dbUtils.User;
import jm.nj.demo23main.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DbutilsDemo {
    /**
     * Jdbc操作数据库的困境
     *
     * @throws SQLException
     */
    @Test
    public void jdbcDemo() throws SQLException {
        //获取数据库连接
        Connection conn = JdbcUtils.getConnection();
        //创建sql执行平台
        PreparedStatement pstmt = conn.prepareStatement("select * from user");

        ResultSet rs = pstmt.executeQuery();

        List<User> users = new ArrayList<User>();
        while (rs.next()){
            User user = new User();
            user.setUid(rs.getInt("uid"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            users.add(user);
        }
        JdbcUtils.closeResoure(conn,pstmt,rs);
        System.out.println(users);

    }

    @Test
    public  void dbutilsDemo() throws SQLException {
        QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
        List<User> list = runner.query("select *  from user",new BeanListHandler<User>(User.class));
        System.out.println(list);
    }

}
